package com.chunlei.check.interceptor;

import com.chunlei.check.annotation.ApiIdempotent;
import com.chunlei.check.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/11/9 19:38
 */
public class ApiIdempotentInterceptor implements HandlerInterceptor
{
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod method = (HandlerMethod) handler;
        ApiIdempotent apiIdempotent = method.getMethodAnnotation(ApiIdempotent.class);
        if (apiIdempotent != null) {
            check(request);// 幂等性校验， 校验通过则放行， 校验失败则抛出异常， 并通过统一异常处理返回友好提示
        }
        return true;
    }

    private void check(HttpServletRequest request) {
        tokenService.checkToken(request);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
    {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception
    {

    }
}
